package com.hjimi.ski.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created By 孙岩
 * on 2022/12/15
 */
public class SDFileHelper {

    public static void savePicture(Context context,String url, String fileName) {
        if (context != null) {
            Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                /**
                 * 成功的回调
                 */
                @Override
                public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                saveFileToSD(context,fileName, Bitmap2Bytes(bitmap));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();
                }

                /**
                 * 失败的回调
                 */
                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    super.onLoadFailed(errorDrawable);
                }
            });
        }
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);

        return baos.toByteArray();
    }

    //往SD卡写入文件的方法 图片
    public static void saveFileToSD(Context context,String filename, byte[] bytes) throws Exception {
        Log.d("sunyan","saveFileToSD");
        //如果手机已插入sd卡,且app具有读写sd卡的权限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/Pic/app";
            Log.d("sunyan","filePath＝＝"+filePath);
            File dir1 = new File(filePath);
            if (!dir1.exists()) {
                dir1.mkdirs();
            }
            filename = filePath + "/" + filename;
            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            FileOutputStream output = new FileOutputStream(filename);
            output.write(bytes);
            //将bytes写入到输出流中
            output.close();
            //关闭输出流
            Log.d("sunyan", "写入成功path=" + filePath);

        } else Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
    }

    //往SD卡写入文件的方法 mp3
    public static void downloadAudioFromNetwork(String url,String path) {
        // 使用网络请求库发送请求，获取网络音频的输入流
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            InputStream inputStream = response.body().byteStream();
            // 将输入流写入本地文件
            String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/Pic/audio";
            File dir1 = new File(filePath);
            if (!dir1.exists()) {
                dir1.mkdirs();
            }
            String filename = filePath + "/" + path;
            FileOutputStream outputStream = new FileOutputStream(filename);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
            Log.d("sunyan", "音频已从网络下载并保存到本地"+filename);
        } catch (Exception e) {
            Log.e("sunyan", "下载音频时出现异常", e);
        }
    }

}
